<?php
namespace Home\Controller;

use Think\Controller;

class ProductsController extends CommonController
{
  protected $this_table = "products";

  public function __construct()
  {
    parent::__construct();
  }

  public function _before_create()
  {
    $this->auth_validate('create', true);
    $this->shops_close();
  }

  public function _before_update()
  {
    $this->auth_validate('update', true);
    $this->shops_close();
  }

  public function _before_status()
  {
    $this->auth_validate('status', true);
    $this->shops_close();
  }

  public function _before_qrcode()
  {
    $this->auth_validate('qrcode', true);
  } 

  public function _before_show()
  {
    $this->auth_validate('show');
  }

  public function _before_index()
  {
    $this->auth_validate('index');
  }

  public function _before_zan()
  {
    $this->auth_validate('zan');
  }

  /**
   * [增/删/改权限检查]
   * @return [type] [description]
   */
  private function auth_validate($action, $is_business = false)
  {
    $this->check_login();

    //是否商户用户
    if (empty($this->shop_id) && $this->types != 1 && $is_business) {
      return_data("error", "$action.{$this->this_table}.deny");
    }
  }

  /**
   * [添加商品]
   * @return [type] [description]
   */
  public function create()
  {
    $model = M($this->this_table);

    $payload = file_get_contents('php://input');
    $data = json_decode($payload, true);

    $default_data = array(
      'shop_id' => $this->shop_id,
      'title' => '',
      'content' => '',
      'created_at' => $this->current_time,
      'updated_at' => $this->current_time);
    $data = array_merge($default_data, $data);

    !$data['logo'] && $data['logo'] = 'http://wdds-app.b0.upaiyun.com/default/logo.jpg';
    $specs = $data['specs'];

    //验证合法性
    if (!$data['name']) {
      return_data("error", $this->this_table.".name.blank");
    }
    if (!isset($data['stock'])) {
      return_data("error", $this->this_table.".stock.blank");
    }
    if (empty($data['product_cate_id'])) {
      return_data("error", $this->this_table.".product_cate_id.blank");
    }
    // if(!$data['title']) return_data("error",$this->this_table.".title.blank");
    // if(!isset($data['sales'])) return_data("error",$this->this_table.".sales.blank");
    // if(!isset($data['is_related'])) return_data("error",$this->this_table.".is_related.blank");

    //product_cate_id 分类合法性检查，对应商户添加对应类
    $map = array(
      'shop_id' => $this->shop_id,
      'id' => $data['product_cate_id']);
    $is_have_id = M("product_cates")->where($map)->getField("id");
    if (!$is_have_id) {
      return_data("error", "create.product_cate_id.to.shop_id.error");
    }
    //商品数量限制

    $products_count = $model->where("shop_id={$this->shop_id} and status<2")->count();
    $products_limit = M('shops')->where("id={$this->shop_id}")->getField('products_limit');
    if ($products_limit != 0 && $products_count >= $products_limit) {
      return_data("error", "products.num.limit", $products_limit);
    }

    //商品重名检查
    $product_id = $model->where("shop_id={$this->shop_id} and name='{$data[name]}' and status < 2")->getField('id');
    if ($product_id) {
      return_data("error", $this->this_table.".name.exist");
    }

    $model->create($data);
    $id = $model->add();
    if (empty($id)) {
      return_data("error", "create.".$this->this_table.".error");//blank
    } else {
      //商品表price存储spec最低价格，修改时同步；
      $littlest_price = $specs_list[0]['price'];
      //规格新增 specs
      if ($specs) {
        $len = 0;
        $prices = array();
        foreach ($specs as $key => $value) {
          if ($value['name']) {
            $specs_list[$len]['name'] = $value['name'];
            $specs_list[$len]['price'] = $value['price'];
            $specs_list[$len]['stock'] = $value['stock'];
            $specs_list[$len]['product_id'] = $id;
            $specs_list[$len]['created_at'] = $this->current_time;
            $len++;

            array_push($prices, $value['price']);
          }
        }
        if ($len > 0) {
          M("specs")->addAll($specs_list);
        }

        //商品表price存储spec最低价格，修改时同步；
        if ($prices) {
          $index = array_search(min($prices), $prices);
          M("products")->where("id=$id")->save(array('price' => $prices[$index]));
        }
      }

      if ($data['photos']) {
        $photo_list = [];
        foreach ($data['photos'] as $photo) {
          $photo_list[] = ['image' => $photo, 'photoable_type' => 'Product', 'photoable_id' => $id];
        }
        $photo_model = M('photos');
        $photo_model->addAll($photo_list);
      }

      return_data("success", "create.".$this->this_table.".success", $id);
    }
  }
  public function cat()
  {
    $model = M($this->this_table);
    $ids = json_decode(trim(I('ids')));

    foreach($ids as $id){
        if (!$id) {
          return_data("error", $this->this_table.".id.blank");
        }

        $info = $model->field("*")->where(array('id' => $id,'status'=>1))->find();
        if (empty($info)) {
          return_data("error", 1);
        }
        //查找分类
        $cat = M("product_cates")->field("*")->where(array('id'=>$info['product_cate_id']))->order("id asc")->find();
        if($cat['status']===0){
          return_data("error", 2);
        }
    };
     return_data("success", "200");
  }
  /**
   * [商品信息]
   * @return [type] [description]
   */
  public function show()
  {
    $model = M($this->this_table);
    $id = trim(I('id'));
    $shop_id = trim(I('shop_id'));

    if($shop_id){
      $this->shop_id = $shop_id;
      $this->shops_close();
    }
    if (!$id) {
      return_data("error", $this->this_table.".id.blank");
    }

    $map = array(
      'id' => $id);
    if ($this->types != 1) {
      $map['status'] = 1;
    }

    //status状态,0:下架；1：上架 ；2：假删除
    $field = "*";
    $info = $model->field($field)->where($map)->find();
    if($info['is_platform'] && $info['app_id']!=$this->app_id){
      return_data("error", "app_id.error");
    }
    //TODO: 需要对普通用户和商户做判断
    //普通用户不看删除和已下架，商户可看
    if (empty($info)) {
      return_data("error", "show.".$this->this_table.".empty");
    } elseif ($info['status'] == 2 && $this->types != 1) {
      return_data("error", "show.".$this->this_table.".deleted");
    } elseif ($info['status'] == 0 && $this->types != 1) {
      return_data("error", "show.".$this->this_table.".down");
    }

    $info['content'] = str_replace(array("\r\n"), "\n", $info['content']);

    //时间转化
    $info['created_at'] = local_time($info['created_at']);
    $info['updated_at'] = $info['updated_at'];

    //查找产品规格
    $map =  array('product_id' => $id);
    $fields = "id, price, name,stock";
    $spec_list = M("specs")->field($fields)->where($map)->order("id asc")->select();
    $info['spec'] = $spec_list;

    if($info['pf_id'] > 0){
      $photos_where = ['photoable_id' => $info['pf_id']];
    } else {
      $photos_where = ['photoable_id' => $id];
    }

    $photo_result = M('photos')->field('image')->where($photos_where)->select();
    $photo_list = [];
    if ($photo_result) {
      foreach ($photo_result as $result) {
        $photo_list[] = $result['image'];
      }
    }
    $info['photos'] = $photo_list;

    //购买限制
    if($info['is_limit'] > 0){
      if ($info['spec']) {
        $buyed_specs = M('order_children')->alias('oc')
          ->join("left join ".C('DB_PREFIX')."orders o on o.id=oc.order_id")
          ->join("left join ".C('DB_PREFIX')."users u on u.id=o.user_id")
          ->field("sum(oc.product_num) as num, oc.product_spec as name")
          ->where("oc.product_id = $id and u.id = {$this->user_id} and o.status not in (3,8)")
          ->group("oc.product_spec")->select();
          foreach($info['spec'] as &$spec){
            $spec['limit_num'] = (int)$info['is_limit'];
            foreach ($buyed_specs as $buyed_spec) {
              if ($spec['name'] == $buyed_spec['name']) {
                $spec['limit_num'] -= $buyed_spec['num'];
                $spec['limit_num'] < 0 && $spec['limit_num'] = 0;
              }
            }
          }

      } else {
        $buyed_num = M('order_children')->alias('oc')
          ->join("left join ".C('DB_PREFIX')."orders o on o.id=oc.order_id")
          ->join("left join ".C('DB_PREFIX')."users u on u.id=o.user_id")
          ->where("oc.product_id = $id and u.id = {$this->user_id} and o.status not in (3,8)")
          ->sum('product_num');
        $info['limit_num'] = $info['is_limit'] - $buyed_num;
        $info['limit_num'] < 0 && $info['limit_num'] = 0;
      }
    }

    //点赞起止时间
    $zan_started_at = strtotime($info['zan_started_at']);
    $zan_ended_at = strtotime($info['zan_ended_at']);

    //当前点赞是否生效
    if ($info['zan_status'] == 1 && $info['zan_price'] && $zan_started_at < $this->current_time) {
      $info['is_zan'] = true;
      //获取点赞头像
      $info['zan_users'] = M('zan_product_users')->alias("z")
               ->join("left join ".C('DB_PREFIX')."users u on u.id=z.user_id")
               ->field("u.id, u.avatar")->where("z.product_id = $id")
               ->order("z.id desc")->limit(30)->select();
      //获取点赞数
      $info['zan_num'] = M('zan_product_users')->where("product_id = $id")->count();

      $info['zan_luck_num'] = M('zan_product_users')->where("product_id = $id and win_no > 0")->count();
      $info['total_luck_num'] = count(explode(',', $info['zan_no']));
      $info['has_luck_num'] = $info['total_luck_num'] - $info['zan_luck_num'];
      $info['zan_luck_users'] = M('zan_product_users')->alias('z')
         ->join("left join ".C('DB_PREFIX')."users u on u.id=z.user_id")
         ->field("u.id, u.avatar")->where("z.product_id = $id and z.win_no > 0")
         ->order("z.id desc")->limit(20)->select();
      $user_zan = M('zan_product_users')->where("product_id = $id and user_id = {$this->user_id}")->find();
      $info['buy_able'] = ($user_zan['win_no'] && !$user_zan['order_id']) ? true : false;

      if (!$user_zan  && $this->current_time < $zan_ended_at) {
        //是否能以点赞价购买
        $info['zan_able'] = true;
      } else {
        $info['zan_able'] = false;
      }
    } else {
      $info['is_zan'] = false;
    }
    if ($info['is_platform'] == 1) {
      if ($info['pf_id'] > 0 && $goods_check = $model->where("id={$info['pf_id']}")->find()){
          $info['product_num'] = $goods_check['product_num'];
      }
      $info['content'] = htmlspecialchars_decode($info['content']);
      $fontstart = strpos($info['content'],"font-family");
      if ($fontstart) {
        $fontend = strpos($info['content'],";",$fontstart);
        $info['content'] = substr_replace($info['content'],"",$fontstart,($fontend - $fontstart + 1));
      }
    }

    if ($info) {
      if (!I("is_business")) {
        M('products')->where("id={$id}")->setInc('hits');
      }

      return_data("success", "show.".$this->this_table.".success", $info);
    } else {
      return_data("error", "show.".$this->this_table.".empty", $info);
    }
  }

  /**
   * [商品列表]
   * @return [type] [description]
   */
  public function index()
  {
    $model = M($this->this_table);

    $page_index = I("page_index", 1);
    $page_size = I("page_size", 50);

    //查询
    $product_cate_id = I("product_cate_id");
    $shop_id = I('shop_id');

    $product = M("product_cates");
    if (I("is_business")) {
      $this->shops_close();
      $where['p.shop_id'] = $shop_id;
      $where['p.status'] = array('in',array(0,1));
    } else {
      $this->shop_id = $shop_id;
      $where['p.shop_id'] = $shop_id;
      $where['p.status'] = 1;
    }
    $shops = M('shops')->field('id')->where(array('id'=>$shop_id,'status'=>2))->find();
    if($shops){
      return_data("error", "shop_id.close.blank");
    }

    if (I("is_platform")) {
      unset($where['p.shop_id']);
      $where['p.app_id'] = $this->app_id;
      $where['p.status'] = 1;
      $where['p.pf_id'] = 0;
      $where['p.is_platform'] = 1;
    }

    if ($product_cate_id) { //类别
      $where['p.product_cate_id'] = $product_cate_id;
    }else if($product_cate_id==='0'){
      $cates = M('product_cates')->field('id,status')->where("shop_id=$shop_id and status=1")->select();    

      foreach($cates as $k => $v){
        $new[] = $v['id'];
      }
      $where['p.product_cate_id'] = array('in',$new);
    }
    $name = trim(I("name"));
    if ($name!='null' && $name!='undefined' && $name!='') {
      $where['p.name'] = array('like',"%$name%");
    }else if($product_cate_id){
      $list = $product->where("id=$product_cate_id")->find();
      if((!$list || $list['status']==0) && $product_cate_id!=='0'){
        return_data("error", "该分类已下架",array('type'=>'down'));
      }
    }
    //排序
    $order = "p.orderby desc,p.id desc ";
    $field = "p.id,p.product_num,p.limit_depot,p.logo,p.name,p.price,p.status,p.proxy_price,p.is_platform,p.pf_id,p.update_at, p.hits";
    $list = $model->alias("p")->field($field)->where($where)->order($order)->page($page_index.",".$page_size)->select();

    if ($list) {
      $index = 0;
      foreach ($list as $key => &$value) {
        if($value['is_platform'] == 1){
          if ($value['pf_id'] > 0) {
            $update_check = $model->where("id={$value['pf_id']} ")->find();
            if($update_check['update_at'] > $value['update_at']){
              unset($update_check['id'],$update_check['pf_id'],$update_check['shop_id'],$update_check['product_cate_id']);
              $model->where("id={$value['id']}")->save($update_check);

              $value = array_merge($value, $update_check);
            }
            $value['product_num'] = $update_check['product_num'];
          }
          $value['brokerage'] = (string)($value['price'] - $value['proxy_price']);
        }
        $specs = M('specs')->field('price, name,stock')->where("product_id=$value[id]")->select();
        $value['specs'] = $specs;
        $value['logo'] = "{$value['logo']}!315x315";
        $value['name'] = sub_str($value['name'], 20);
      }

      return_data("success", "index.".$this->this_table.".success", $list);
    } else {
      return_data("error", "index.".$this->this_table.".empty");
    }
  }

  /**
   * [修改商品]
   * @return [type] [description]
   */
  public function update()
  {
    $model = M($this->this_table);

    $payload = file_get_contents('php://input');
    $data = json_decode($payload, true);
    $data['updated_at'] = $this->current_time;

    unset($data['shop_id']);
    unset($data['created_at']);

    $model->create($data);
    $map = array(
      'id' => $data['id'],
      'shop_id' => $this->shop_id);
    $result = $model->where($map)->save($data);
    if ($result) {

      //商品表price存储spec最低价格，修改时同步；
      // $littlest_price = $specs_list[0]['price'];

      //规格新增 specs
      // $specs = $data['specs'];
      if ($data['specs']) {
        $len = 0;
        $prices = array();

        foreach ($data['specs'] as $key => $value) {
          if ($value['name']) {
            $specs_list[$len]['name'] = $value['name'];
            $specs_list[$len]['price'] = $value['price'];
            $specs_list[$len]['stock'] = $value['stock'];
            $specs_list[$len]['product_id'] = $data['id'];
            $specs_list[$len]['updated_at'] = $this->current_time;
            $specs_list[$len]['created_at'] = $this->current_time;

            $len++;

            array_push($prices, $value['price']);
          }
        }

        if ($len > 0) {
          M("specs")->where("product_id={$data[id]}")->delete();
          M("specs")->addAll($specs_list);
        }

        if ($prices) {
          $index = array_search(min($prices), $prices);
          M("products")->where("id=$data[id]")->save(array('price' => $prices[$index]));
        }
      }else{
        M("specs")->where("product_id={$data[id]}")->delete();
      }

      if ($data['photos']) {
        M('photos')->where(['photoable_type' => 'Product', 'photoable_id' => $data['id']])->delete();
        $photo_list = [];
        foreach ($data['photos'] as $photo) {
          $photo_list[] = ['image' => $photo, 'photoable_type' => 'Product', 'photoable_id' => $data['id']];
        }
        $photo_model = M('photos');
        $photo_model->addAll($photo_list);
      } else {
        $count = M('photos')->where("photoable_id={$data['id']}")->count();
        if ($count) {
          M('photos')->where("photoable_id={$data['id']}")->delete();
        }
      }

      return_data("success", "update.".$this->this_table.".success");
    } else {
      return_data("error", "update.".$this->this_table.".error", $map);
    }
  }

  /**
   * [商品状态操作]
   * status 0:下架；1：上架；2：删除
   * @return [type] [description]
   */
  public function status()
  {
    $model = M($this->this_table);

    $payload = file_get_contents('php://input');
    $data = json_decode($payload, true);
 
    $status_arr = array(0, 1, 2);
    if (!in_array($data['status'], $status_arr)) {
      return_data("error", $this->this_table.".status.error");
    }

    $map = array(
      'id' => $data['id'],
      'shop_id' => $this->shop_id);
    $data['updated_at'] = $this->current_time;

    $list = $model->where($map)->find();

    $sp = M('specs')->field('stock')->where("product_id=$list[id]")->select();
    if($sp){
      $spec = true;
      foreach($sp as $v){
        if($v['stock']>0){
          $spec = false;
        }
      }
      if($spec && $data['status'] == 1){
        return_data("error", "product_num.nix");
      } 
    }else{
      if($list['is_platform']==1 && $data['status'] == 1 && $goods = $model->where("id=$list[pf_id]")->find()){
        
        if($goods['status']!=1){
          return_data("error","goods_status.error");
        }
        if($goods['product_num'] <=0){
          return_data("error","product_num.nix");
        }
      }

      if($list['is_platform']==0 && $list['product_num'] <=0 && $data['status'] == 1)
      {
        return_data("error", "product_num.nix");
      }      
    }

    $result = $model->where($map)->save($data);

    if ($result) {
      return_data("success", "{$this->this_table}.status.success");
    } else {
      return_data("error", "{$this->this_table}.status.error");
    }
  }

  public function qrcode()
  {
    $payload = file_get_contents('php://input');
    $data = json_decode($payload, true);

    $map = array('id' => $data['id']);
    $product = M('products')->alias('p')->where("p.id={$data['id']}")
                           ->join("left join ".C('DB_PREFIX')."users u on u.shop_id=p.shop_id")
                           ->field('p.*,u.avatar as user_avatar,u.nickname as user_name')
                           ->find();

    //获取商品合成缩略图
    $product_logo = save_img($product['logo']);
    //$debug_token = get_xcx_token(3);
    //获取商品小程序码，暂未做缓存
    $wxacode = get_product_wxacode($product, $this->app_id);
    $user_avatar =  save_img($product['user_avatar']);

    $filename = md5(uniqid()).'.jpg';
    $month = Date('Ym');
    $product_wxa_path = THINK_PATH."../upload/watermark/{$month}/";
    $poster_img = "{$product_wxa_path}{$filename}";

    if (!file_exists($product_wxa_path)) {
      mkdir($product_wxa_path, 0777, true);
    }
    $product['user_name'] = mb_strlen($product['user_name'], 'UTF8') > 6 ? mb_substr($product['user_name'], 0, 6, 'UTF8')."…" : $product['user_name'];
    //test
    if ($product['is_platform'] == 1) {
      $product['content'] = $product['descrip'];
    }
    $content = "{$product['name']} {$product['content']}";
    $content = str_replace(array("\r\n", "\r", "\n"), " ", $content);
    $poster = array(
      'product_logo' => $product_logo['tmp_name'],
      'qrcode' => $wxacode['tmp_name'],
      'share_title' => $data['is_zan'] ? "邀请你参与点赞" : "分享给你一个商品",
      'product_descrip' => $content,
      'user_name' =>  $product['user_name'],
      'user_avatar' => $user_avatar['tmp_name'],
      "product_price" => $data['is_zan'] ? $product['zan_price'] : $product['price'],
      "text_font" => './Public/fonts/fzltkh.TTF'
    );
    Vendor('Grafika.createImage');
    $creater = new \posterCreater; 
    $creater->create($poster, "{$product_wxa_path}{$filename}");

    $month = date('Ym');
    $file['savepath'] = "products/wxacode/{$month}/";
    $file['savename'] = $filename;
    $file['tmp_name'] = "{$product_wxa_path}{$filename}";
    $file['type'] = 'image/jpeg';
    $file['size'] = filesize("{$product_wxa_path}{$filename}");

    $product_img = upload_local_file($this->app_id, $file);

    @unlink($product_logo['tmp_name']);
    @unlink($user_avatar['tmp_name']);
    @unlink($wxacode['tmp_name']);

    return_data("success", "product.wxacode.success", $product_img);
  }

  /**
   * [点赞]
   * @return [type] [description]
   */
  public function zan()
  {
    $payload = file_get_contents('php://input');
    $data = json_decode($payload, true);
    $product_id = $data['product_id'];
    $product_map = array(
      'id' => $product_id,
      "zan_started_at <= CURRENT_TIMESTAMP",
      "zan_ended_at >= CURRENT_TIMESTAMP");
    $product = M('products')->field('zan_no')->where($product_map)->find();
    if (!$product) {
      return_data("error", 'product.zan.product.invalid', $product_id);
    }

    $zan_map = array(
      'product_id' => $product_id,
      'user_id' => $this->user_id );
    $zan = M('zan_product_users')->where($zan_map)->find();
    if ($zan) {
      return_data("error", 'product.zan.repeated');
    }
    $zan_map['created_at'] = $zan_map['updated_at'] = $this->current_time;
    M('zan_product_users')->create($zan_map);
    $id = M('zan_product_users')->add();
    if ($id) {
      $zan_no =  M('zan_product_users')->where("product_id = $product_id")->count();
      $zan_array = explode(',', $product['zan_no']);
      if (in_array($zan_no, $zan_array)) {
        M('zan_product_users')->where("id = $id")->save(array('win_no' => $zan_no));

        send_zan_win_message_to_shop($zan_map);

        return_data("success", 'product.zan.success', array('win' => 'true', 'win_no' => $zan_no));
      } else {
        return_data("success", 'product.zan.success', array('win' => 'false'));
      }
    } else {
      return_data("error", 'product.zan.error');
    }
  }
}
